# 作者: 家里蹲 吴越洋
# 2023年03月08日18时12分21秒
from socket import *
import struct
import os

class Server:#端口号port  ip地址ip
    def __init__(self,ip,port):
        self.ip=ip
        self.port=port
        self.path = '.'
        self.server_socket:socket=None
        self.new_socket:socket=None

    def tcp_init(self):
        server_socket=socket(AF_INET,SOCK_STREAM)
        # 重用对应地址和端口
        server_socket.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
        # 本地IP地址和端口
        address=(self.ip,self.port)
        server_socket.bind(address)
        # 端口激活
        server_socket.listen(100)
        self.server_socket=server_socket

    def send_train(self,data:str):
        data_bytes=data.encode('utf8')
        data_len=len(data_bytes)
        # 发火车头，4个字节
        self.new_socket.send(struct.pack('I',data_len))
        # 发内容
        self.new_socket.send(data_bytes)

    def recv_train(self,new_socket:socket):
        # 接受火车头
        train_len=new_socket.recv(4)
        # 解包获得长度
        train_content_len=struct.unpack('I',train_len)[0]
        # 接受内容
        train_content:bytes=new_socket.recv(train_content_len)
        return train_content.decode('utf8')

    def do_ls(self):
        """
        当前路径的信息传输给客户端
        :return:
        """
        data=''
        for file in os.listdir(self.path):
            data+=file+' '*5+str(os.stat(file).st_size)+'\n'
        self.send_train(data)

    def deal_command(self):
        new_socket,new_addr=self.server_socket.accept()
        self.new_socket=new_socket
        print(new_addr)
        while True:
            # 接受客户端发来的命令
            command=self.recv_train(new_socket)
            if command[:2]=='ls':
                self.do_ls()

if __name__ == '__main__':
    s=Server('',3000)
    s.tcp_init()
    s.deal_command()